package com.woniuxy.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 管理员过滤器
 *  @author zhang
 * @create 2021-08-18-19:46
 */
/*@WebFilter("/admin/*")*/
@Order(value = 1)
public class AdminFilter implements Filter {
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/admin/manager/login")));

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {		HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
        String contextPath = req.getServletContext().getContextPath();
        String uri = req.getRequestURI().toString();
        if(req.getRequestURI().equals(contextPath+"/admin")) {
            chain.doFilter(request, response);
            return;
        }
        System.out.println(uri);
        boolean allowedPath = ALLOWED_PATHS.contains(uri);

        if(allowedPath){
            //放行
            chain.doFilter(request, response);
            return;
        }
        if(req.getSession().getAttribute("manager")==null) {
            resp.sendRedirect(contextPath+"/admin/manager/login");

        }else {
            //放行
            chain.doFilter(request, response);
        }
    }
}
